package com.zhongxi.guoyuan.view.user;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.UploadResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.FileTool;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.view.rewardCoin.RewardAddressListActivity;

import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class UserInfoSettingActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivHead;
    private TextView tvStoreName;
    private RelativeLayout relaHead;
    private RelativeLayout relaName;
    private RelativeLayout relaAddress;
    private Bitmap bitmap;
    private String type;
    private EditText etSetName;
    private RelativeLayout relaModifyPassword;
    private MediaScannerConnection mMediaonnection;
    private File origPicFile;
    private File absolutePicFile;
    private String timeStamp;
    private AlertDialog dialog;
    private DialogInterface.OnKeyListener onKeyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
            if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                return true;
            }
            return false;
        }
    };

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_user_info_setting);
        initTitle();
        tvTitle.setText("个人设置");
        ivHead = (ImageView) findViewById(R.id.ivHead);
        tvStoreName = (TextView) findViewById(R.id.tvStoreName);
        relaHead = (RelativeLayout) findViewById(R.id.relaHead);
        relaName = (RelativeLayout) findViewById(R.id.relaName);
        relaAddress= (RelativeLayout) findViewById(R.id.relaModifyAddress);
        relaModifyPassword = (RelativeLayout) findViewById(R.id.relaModifyPassword);
        if (null != MyApplication.getInstance().getUserName() && !"".equals(MyApplication.getInstance().getUserName())) {
            tvStoreName.setText(MyApplication.getInstance().getUserName());
        }
        Glide.with(this).load(Url.BASE_URL + MyApplication.getInstance().getAvatar())
                .placeholder(R.mipmap.iv_eg)
//                .transform(new GlideRoundTransform(this, 20))
                .into(ivHead);
    }


    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        relaHead.setOnClickListener(this);
        relaName.setOnClickListener(this);
        relaAddress.setOnClickListener(this);
        relaModifyPassword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.relaHead:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
                } else {
                    popHeadDialog();
                }
                break;
            case R.id.relaName:
                popNameDialog();
                break;
            case R.id.relaModifyPassword:
                startAct(ModifyPasswordActivity.class);
                break;
            case R.id.relaModifyAddress:
                startAct(RewardAddressListActivity.class);
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        popHeadDialog();
    }

    /**
     * 弹出头像
     */
    private void popHeadDialog() {
        initFile();
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_head_setting, null);
        dialog = new AlertDialog.Builder(context).create();
        dialog.setView(layout);
        dialog.setOnKeyListener(onKeyListener);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView tvSelect = (TextView) layout.findViewById(R.id.tvSelect);
        TextView tvTakePhone = (TextView) layout.findViewById(R.id.tvTakePhone);
        tvSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   //相册
                getPhoto();
                dialog.dismiss();
            }
        });
        tvTakePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
                dialog.dismiss();
            }
        });
    }

    private void initFile() {
        // 输出裁剪的临时文件的时间
        timeStamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        // 照片命名
        String origFileName = "pic_origin_" + timeStamp + ".jpg";
        String cropFileName = "pic_after_crop_" + timeStamp + ".jpg";

        // 裁剪头像的绝对路径
        String absolutePicPath = FileTool.getRootFilePath() + cropFileName;
        absolutePicFile = new File(absolutePicPath);
        origPicFile = new File(FileTool.getRootFilePath(), origFileName);
    }

    private void getPhoto() {  //相册
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, 1);
    }

    private void takePhoto() {   //相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri picUri = null;
        if (Build.VERSION.SDK_INT < 24) {
            picUri = Uri.fromFile(origPicFile);
        } else {
            picUri = FileProvider.getUriForFile(context, context.getResources().getString(R.string.authorities), origPicFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
        startActivityForResult(intent, 0);// 采用ForResult打开
    }


    /**
     * 弹出设置名称dialog
     */
    private void popNameDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_name_setting, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setView(layout);

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        TextView tvComplete = (TextView) layout.findViewById(R.id.tvComplete);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        TextView tv_oldName = (TextView) layout.findViewById(R.id.tv_oldName);
        tv_oldName.setText(MyApplication.getInstance().getUserName());
        etSetName = (EditText) layout.findViewById(R.id.etSetName);
        //取消
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //设置名称
        tvComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etSetName.getText().toString().trim())) {
                    showShortToast("名称不能为空!");
                } else {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("username", etSetName.getText().toString().trim());
                    type = "shopname";
                    getServer(Url.SET_USERNAME, map, "", false, null, "post");
                    dialog.dismiss();
                }
            }
        });
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("shopname".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                MyApplication.getInstance().sharedPrefrences.edit().putString("username", etSetName.getText().toString().trim()).commit();
                tvStoreName.setText(etSetName.getText().toString().trim());
                showShortToast("设置用户名成功！");
            } else if ("uploadImg".equals(type)) {
                UploadResult result = gson.fromJson(response, UploadResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (null != result.getAvatar() && !"".equals(result.getAvatar())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", result.getAvatar()).commit();
                    showShortToast("设置用户头像成功！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (result.getCode() == 100) {
                showShortToast("参数错误");
            } else if (result.getCode() == 1001) {
                showShortToast("用户未登录");
            } else if (result.getCode() == 1666) {
                showShortToast("服务不可用，服务器异常");
            } else if (result.getCode() == 4005) {
                showShortToast("头像上传失败");
            } else if (result.getCode() == 4006) {
                showShortToast("上传文件大小超限");
            } else if (result.getCode() == 4007) {
                showShortToast("不是有效的图片文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            switch (requestCode) {
                case 0:            //相机
                    if (resultCode == RESULT_OK) {
                        final String img_path = FileTool.getRootFilePath() + "pic_origin_" + timeStamp + ".jpg";   //    /storage/emulated/0/meirongyuan/head.jpg
//                        MediaStore.Images.Media.insertImage(getContentResolver(), img_path, "pic_origin_" + timeStamp, null);   //将拍的img_path的照片保存系统相册中
                        mMediaonnection = new MediaScannerConnection(context, new MediaScannerConnection.MediaScannerConnectionClient() {   //刷新系统相册,显示刚拍的图片
                            @Override
                            public void onMediaScannerConnected() {
                                mMediaonnection.scanFile(img_path, "pic_origin_" + timeStamp);
                            }

                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                mMediaonnection.disconnect();
                            }
                        });
                        mMediaonnection.connect();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            Uri picUri = FileProvider.getUriForFile(context, context.getResources().getString(R.string.authorities), origPicFile);
                            startPhotoZoom(picUri);
                        } else {
                            startPhotoZoom(Uri.fromFile(origPicFile));
                        }
                    }
                    break;
                case 1:                  //相册
                    if (resultCode == RESULT_OK) {
                        Uri sourceUri = data.getData();
                        startPhotoZoom(sourceUri);
                    }
                    break;
                case 2:
                    if (data != null) {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
                            bitmap = extras.getParcelable("data");
                            try {
                                FileOutputStream fout = new FileOutputStream(absolutePicFile);
                                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);  //  0-100 100为不压缩
                                fout.flush();
                                fout.close();
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            ivHead.setImageBitmap(bitmap);
                            uploadHead(absolutePicFile);
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户上传头像
     *
     * @param absolutePath
     */
    private void uploadHead(File absolutePath) {
        try {
            type = "uploadImg";
            uploadServer(Url.UPLOAD_AVATAR, false, null, absolutePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startPhotoZoom(Uri imageUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(imageUri, "image/*");    // 源文件地址
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);    // aspectX aspectY是宽高比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);  // outputX outputY 是裁剪图片的宽高
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);   // 是否返回uri
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, 2);
    }
}
